package com.ocm.commerceinteraction.ui;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.MainActivity;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.view.HTML5CustomWebView;
import com.ocm.commerceinteraction.util.view.ProgressWebView;
import com.ocm.commerceinteraction.util.view.percentsupport.PercentRelativeLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.Date;


public class CenterFragment_v2 extends BaseFragment {
    View view;
    HTML5CustomWebView adWebview;
    CenterFragment_v2 context;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_center_v2, container, false);
        String url = "http://bchat.ocmcom.com/HUser/user.html?time=" + new Date().getTime();
//        String url = "http://www.baidu.com";
        context = this;
        adWebview = new HTML5CustomWebView(getActivity(), getActivity(),"我的",url, context);
        adWebview.setWebChromeClient(new MyWebChromeClient());
        adWebview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        adWebview.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return true;
            }
        });
        adWebview.loadUrl(url);
        initView();
        return adWebview.getLayout();
    }




    @Override
    void initView() {
//        homeFragment = this;
//        topTitle.setText("我的");
//        backBtn.setVisibility(View.GONE);
//        loadData();
    }


    //加载数据
    private void loadData() {
        adWebview.getSettings().setJavaScriptEnabled(true);
        String url = "http://bchat.ocmcom.com/HUser/user.html?time=" + new Date().getTime();

        //       String url = "http://www.jq22.com/yanshi1845";
        WebSettings settings = adWebview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        adWebview.setVerticalScrollBarEnabled(true);
        adWebview.setHorizontalScrollBarEnabled(true);
        adWebview.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return true;
            }
        });
//        adWebview.setWebChromeClient(new WebChromeClient() {
//            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
//                mUploadMessage = uploadMsg;
//                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//                i.addCategory(Intent.CATEGORY_OPENABLE);
//                i.setType("*/*");
//                getActivity().startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
//            }
//
//            // For Android 3.0+
//            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
//                mUploadMessage = uploadMsg;
//                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//                i.addCategory(Intent.CATEGORY_OPENABLE);
//                i.setType("*/*");
//                getActivity().startActivityForResult(
//                        Intent.createChooser(i, "File Browser"),
//                        FILECHOOSER_RESULTCODE);
//            }
//
//            //For Android 4.1
//            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//                mUploadMessage = uploadMsg;
//                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//                i.addCategory(Intent.CATEGORY_OPENABLE);
//                i.setType("*/*");
//                getActivity().startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
//            }
//
//            // For Android 5.0+
//            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
//                mUploadCallbackAboveL = filePathCallback;
//                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//                i.addCategory(Intent.CATEGORY_OPENABLE);
//                i.setType("*/*");
//                getActivity().startActivityForResult(
//                        Intent.createChooser(i, "File Browser"),
//                        FILECHOOSER_RESULTCODE);
//                return true;
//            }
//        });
        adWebview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {// 载入进度改变而触发
                if (progress == 100) {
                    //handler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
                }

                super.onProgressChanged(view, progress);
            }

            //扩展支持alert事件
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setTitle("xxx提示").setMessage(message).setPositiveButton("确定", null);
                builder.setCancelable(false);
                builder.setIcon(R.mipmap.logo);
                AlertDialog dialog = builder.create();
                dialog.show();
                result.confirm();
                return true;
            }

            //扩展浏览器上传文件
            //3.0++版本
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooserImpl(uploadMsg);
            }

            //3.0--版本
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooserImpl(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }

            // For Android > 5.0
            public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams) {
                openFileChooserImplForAndroid5(uploadMsg);
                return true;
            }
        });

        adWebview.addJavascriptInterface(this, "ocm");
        //newsWebview.setBarHeight(3);
        adWebview.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
//        getActivity().setContentView(adWebview);
        syncCookie(getActivity(), url);
        adWebview.loadUrl(url);
    }


    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }


    public ValueCallback<Uri[]> mUploadMessageForAndroid5;

    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    private ValueCallback<Uri> mUploadMessage;
    ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 1;

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == FILECHOOSER_RESULTCODE) {
//            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
//            Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
//            if (mUploadCallbackAboveL != null) {
//                onActivityResultAboveL(requestCode, resultCode, data);
//            } else if (mUploadMessage != null) {
//                mUploadMessage.onReceiveValue(result);
//                mUploadMessage = null;
//            }
//        }
//    }


    // 一下2个方法解决  onShowFileChooser只加载一次的问题
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogHelper.i("onActivityResult");
        if(requestCode==adWebview.FILECHOOSER_RESULTCODE)
        {
            if (null == adWebview.mUploadMessage && null == adWebview.mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
            if (adWebview.mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            }
            else  if (adWebview.mUploadMessage != null) {
                adWebview.mUploadMessage.onReceiveValue(result);
                adWebview.mUploadMessage = null;
            }
        }
        MainActivity.getInstance().tabHost.setCurrentTab(1);
        MainActivity.getInstance().tabHost.setCurrentTab(3);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        LogHelper.i("onActivityResultAboveL");
        if (requestCode != adWebview.FILECHOOSER_RESULTCODE
                || adWebview.mUploadCallbackAboveL == null) {
            return;
        }

        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {

            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();

                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        adWebview.mUploadCallbackAboveL.onReceiveValue(results);
        adWebview.mUploadCallbackAboveL = null;
        return;
    }


    /**
     * js 测试toast
     */
    @JavascriptInterface
    public void show() {
        Toast.makeText(getActivity(), "hello kitty", Toast.LENGTH_SHORT).show();
    }

    /**
     * js 使用返回
     */
    @JavascriptInterface
    public void keyBack() {
        MainActivity.getFragmentMangerinstance().popBackStack();
    }


    void Click(View view) {

    }


    /**
     * Sync Cookie
     */
    private void syncCookie(Context context, String url) {
        try {
            //Log.d("Nat: webView.syncCookie.url", url);
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            LogHelper.i(" GlobalApplication.localCookie:" + GlobalApplication.localCookie.getCookies());

            StringBuilder sbCookie = new StringBuilder();
            sbCookie.append(String.format("PHPSESSID=%s", GlobalApplication.localCookie.getCookies().get(0).getValue()));
            sbCookie.append(String.format(";domain=%s", "bchat.ocmcom.com"));
            sbCookie.append(String.format(";path=%s", "/"));

            String cookieValue = sbCookie.toString();
            cookieManager.setCookie(url, cookieValue);
            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                // Log.d("Nat: webView.syncCookie.newCookie", newCookie);
            }
        } catch (Exception e) {
            // Log.e("Nat: webView.syncCookie failed", e.toString());
        }
    }


    boolean loadFlag = false;
    @Override
    public void onResume() {
        super.onResume();
        if (adWebview != null) {
            adWebview.onResume();
            if (!loadFlag) {
                LogHelper.i("loadFlag");
                loadFlag = true;
                MainActivity.getInstance().tabHost.setCurrentTab(1);
                MainActivity.getInstance().tabHost.setCurrentTab(3);
            }
        }
//        loadData();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (adWebview != null) {
            adWebview.saveState(outState);
        }
    }


    private class MyWebChromeClient extends WebChromeClient {
        private Bitmap mDefaultVideoPoster;
        @Override
        public void onShowCustomView(View view,
                                     CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
//            HTML5CustomWebView.this.setVisibility(View.GONE);
//            if (mCustomView != null) {
//                callback.onCustomViewHidden();
//                return;
//            }
//            mCustomViewContainer.addView(view);
//            mCustomView = view;
//            mCustomViewCallback = callback;
//            mCustomViewContainer.setVisibility(View.VISIBLE);
        }

        @Override
        public void onHideCustomView() {
//            if (mCustomView == null) {
//                return;
//            }
//            mCustomView.setVisibility(View.GONE);
//            mCustomViewContainer.removeView(mCustomView);
//            mCustomView = null;
//            mCustomViewContainer.setVisibility(View.GONE);
//            mCustomViewCallback.onCustomViewHidden();
//            HTML5CustomWebView.this.setVisibility(View.VISIBLE);
            super.onHideCustomView();
        }

        /**
         * 网页加载标题回调
         * @param view
         * @param title
         */
        @Override
        public void onReceivedTitle(WebView view, String title) {
            Log.d("zttjiangqq", "当前网页标题为:" + title);
            adWebview.wv_tv_title.setText(title);
        }

        /**
         * 网页加载进度回调
         * @param view
         * @param newProgress
         */
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // 设置进行进度
            getActivity().getWindow().setFeatureInt(
                    Window.FEATURE_PROGRESS, newProgress * 100);
            adWebview.webview_tv_progress.setText("正在加载,已完成" + newProgress + "%...");
            adWebview.webview_tv_progress.postInvalidate(); // 刷新UI
            LogHelper.i("进度为:" + newProgress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 JsResult result) {
            return super.onJsAlert(view, url, message, result);

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
//            ((Activity) mContext).startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
			startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType ) {
            LogHelper.i("For Android 3.0+");
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
//            ((Activity) mContext).startActivityForResult(
//                    Intent.createChooser(i, "File Browser"),
//                    FILECHOOSER_RESULTCODE);
					startActivityForResult(
							Intent.createChooser(i, "File Browser"),
							FILECHOOSER_RESULTCODE);
        }
        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
            LogHelper.i("For Android 4.1)");
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
//            ((Activity) mContext).startActivityForResult( Intent.createChooser( i, "File Browser" ),FILECHOOSER_RESULTCODE );
			startActivityForResult( Intent.createChooser( i, "File Browser" ),FILECHOOSER_RESULTCODE );
        }

        // For Android 5.0+
        public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            LogHelper.i("For Android 5.0+");
            mUploadCallbackAboveL = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
//            ((Activity) mContext).startActivityForResult(
//                    Intent.createChooser(i, "File Browser"),
//                    FILECHOOSER_RESULTCODE);
		startActivityForResult(
					Intent.createChooser(i, "File Browser"),
					FILECHOOSER_RESULTCODE);
            return true;
        }

    }
}
